<?php


namespace App\Services\Home;

use App\Models\Asin;
use App\Models\Category;
use App\Models\Product;
use Keepa\API\ResponseStatus;
use Keepa\KeepaAPI;
use Keepa\API\Request;

class CategoryService
{
    protected $category;

    public function __construct(Category $category)
    {
        $this->category = $category;
    }

    /**
     * @param array $params
     * @return \Illuminate\Http\JsonResponse|\Keepa\API\Response|object
     * @throws \Exception
     */
    public function getCategories($params = [])
    {
        $categories = Category::where($params)->get();

        //获取一级分类
        if (!count($categories)) {
            $categories = [];
            $api = new KeepaAPI(env('KEEPA_API_KEY'));

            if (!isset($params['catId'])) {
                //顶级分类
                $catId = 0;
                $r = Request::getCategoryLookupRequest((int)$params['domainId'], true, $catId);
                $response = $api->sendRequestWithRetry($r);

                if ($response->status == ResponseStatus::OK) {

                    foreach ($response->categories as $category) {
                        if ($category->children) {
                            $category->childrens = implode(',', $category->children);
                            $category->children_num = count($category->children);
                        } else {
                            $category->children_num = 0;
                        }
                        unset($category->children);
                        $category->created_at = time();
                        $categories[] = (array)$category;
                    }
                    Category::insert($categories);
                }
            } else {
                $catId = $params['catId'];
                $cat_arr = explode(',', $catId);
                $splits = array_chunk($cat_arr, 10);
                foreach ($splits as $split) {
                    $cat_str = implode(',', $split);
                    $r = Request::getCategoryLookupRequest((int)$params['domainId'], true, $cat_str);
                    $response = $api->sendRequestWithRetry($r);

                    if ($response->status == ResponseStatus::OK) {
                        foreach ($response->categories as $category) {
                            if ($category->children) {
                                $category->childrens = implode(',', $category->children);
                                $category->children_num = count($category->children);
                            } else {
                                $category->children_num = 0;
                            }
                            unset($category->children);
                            $category->created_at = time();
                            $categories[] = (array)$category;
                        }
                        Category::insert($categories);
                    }
                }
            }
        }
        return Success('ok', $categories);
    }

    public function getProducts($params = [])
    {
        $where = ['domainId' => $params['domainId'], 'catId' => $params['catId']];
        if (isset($params['recent_update']) && $params['recent_update']){
            $time_gte = strtotime("-3 days");
            $time_lte = time();
            $where['create_time'] = ['$gte' => $time_gte, '$lte' => $time_lte];
        }
        $where['sort_key'] = ['$gte' => $params['sales_rank_low'], '$lte' => $params['sales_rank_high']];
        $asins = Asin::where($where)->get();

        //本地不存在，从keepa获取
        if (count($asins) < $params['numbers']) {
            $param = new \Keepa\objects\ProductFinderRequest();
            $param->current_SALES_gte = $params['sales_rank_low'];
            $param->current_SALES_lte = $params['sales_rank_high'];
            $param->rootCategory = $params['catId'];
            $param->perPage = $params['numbers'];
            $param->sort = ['current_SALES', 'desc'];
            $param->singleVariation = true;

            $api = new KeepaAPI(env('KEEPA_API_KEY'));
            $r = Request::getFinderRequest((int)$params['domainId'], $param);
            $response = $api->sendRequestWithRetry($r);

            if ($response->status == ResponseStatus::OK) {
                if (count($response->asinList)){
                    $inserts = [];
                    foreach ($response->asinList as $k => $asin) {
                        $inserts[] = [
                            'domainId' => (int)$params['domainId'],
                            'catId' => (int)$params['catId'],
                            'catName' => $params['catName'],
                            'sort_key' => (int)($k + $params['sales_rank_low']),
                            'asin' => $asin,
                            'create_time' => time(),
                        ];
                    }
                    ///插入前删除旧数据
                    Asin::where(['catId' => (int)$params['catId'], 'sort_key' => ['$gte' => $params['sales_rank_low'], '$lte' => $params['sales_rank_high']]])->delete();
                    Asin::insert($inserts);
                    $asins = $inserts;
                    return Success('ok', $asins);
                }else{
                    return Error('该分类指定条件下暂无asin！');
                }
            }
            return Error('请求失败，请稍后重试！');
        }
        return Success('任务添加成功，请到任务列表获取产品！', $asins);
    }

    public function getProductInfo($params = [])
    {
        $products = Product::whereIn('asin', $params['asins'])->orderBy('sales_rank_current', 'asc')->get();

        //本地不存在，从keepa获取
        if (!count($products)) {
            $api = new KeepaAPI(env('KEEPA_API_KEY'));
            $r = Request::getProductRequest((int)$params['domainId'], null, null, null, 0, 0, $params['asins'], ['stats' => 180, 'rating' => 1]);
            $response = $api->sendRequestWithRetry($r);

            if ($response->status == ResponseStatus::OK) {
                $inserts = array();
                foreach ($response->products as $product) {
                    if ($product->imagesCSV){
                        $image_arr = explode(',',$product->imagesCSV);
                        $inserts[] = [
                            'domainId' => $product->domainId,
                            'asin' => $product->asin,
                            'image' => $image_arr[0],
                            'imagesCSV' => $product->imagesCSV,
                            'title' => $product->title,
                            'manufacturer' => $product->manufacturer,
                            'brand' => $product->brand,
                            'productGroup' => $product->productGroup,
                            'partNumber' => $product->partNumber,
                            'color' => $product->color,
                            'size' => $product->size,
                            'salesRankReference' => $product->salesRankReference,
                            'categoryTree' => $product->categoryTree,
                            'description' => $product->description,
                            'sales_rank_current' => $product->stats->current[3],
                            'sales_rank_30_days_avg' => $product->stats->avg30[3],
                            'sales_rank_90_days_avg' => $product->stats->avg90[3],
                            'sales_rank_180_days_avg' => $product->stats->avg180[3],
                            'buy_box_current' => number_format($product->stats->current[1] / 100, 2),
                            'buy_box_30_days_avg' => number_format($product->stats->avg30[1] / 100, 2),
                            'buy_box_90_days_avg' => number_format($product->stats->avg90[1] / 100, 2),
                            'buy_box_180_days_avg' => number_format($product->stats->avg180[1] / 100, 2),
                            'monthlySold' => $product->monthlySold,
                            'reviews_rating' => number_format($product->stats->current[16] / 10, 2),
                            'reviews_review_count' => $product->stats->current[17],
                            'packageHeight' => $product->packageHeight,
                            'packageLength' => $product->packageLength,
                            'packageWidth' => $product->packageWidth,
                            'packageWeight' => $product->packageWeight,
                            'itemHeight' => $product->itemHeight,
                            'itemLength' => $product->itemLength,
                            'itemWidth' => $product->itemWidth,
                            'itemWeight' => $product->itemWeight,
                            'lastUpdate' => translate_keepa_time($product->lastUpdate),
                            'lastPriceChange' => translate_keepa_time($product->lastPriceChange),
                            'created_at' => time()
                        ];
                    }

                }
                Product::insert($inserts);
                $products = $inserts;
            } else {
                $products = [];
                $message = $response->error;
            }
        }
        if (count($products)) {
            return Success('ok', $products);
        } else {
            return Error($message);
        }
    }
}
